package com.wanpinghui.supplier.business;


import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.addrbook.CustomerInfoActivity;
import com.wanpinghui.supplier.business.adapter.CircleListAdapter;
import com.wanpinghui.supplier.common.BaseFragment;
import com.wanpinghui.supplier.message.nim.NimManager;
import com.wanpinghui.supplier.object.HomePageActivity;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.RxEventType;
import com.wanpinghui.wphlibrary.common.dialog.BaseDialogManager;
import com.wanpinghui.wphlibrary.common.toast.ToastManager;
import com.wanpinghui.wphlibrary.model.business.BusinessService;
import com.wanpinghui.wphlibrary.model.business.bean.CommentBean;
import com.wanpinghui.wphlibrary.model.business.bean.DynamicBean;
import com.wanpinghui.wphlibrary.model.business.bean.DynamicPageData;
import com.wanpinghui.wphlibrary.model.business.bean.ThumbUpBean;
import com.wanpinghui.wphlibrary.model.message.bean.CustomerNotificationContent;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.yunshl.yunshllibrary.rxbus.RxBus;
import com.yunshl.yunshllibrary.rxbus.SubscriptionBean;
import com.yunshl.yunshllibrary.view.YunShlPopupWinow;

import org.xutils.common.util.DensityUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.lang.ref.WeakReference;
import java.util.List;

import retrofit.callback.YRequestCallback;
import rx.Subscription;
import rx.functions.Action1;


/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2018/1/23
 ***/
@ContentView(R.layout.layout_activity_business_circle)
public class BusinessCircleFragment extends BaseFragment implements CircleListAdapter.OnOperationListener, NimManager.INimNotificationListener {
    private static final int REQUEST_PUBLISH = 1;
    public static final int REFRESH_HAVE_NEW = 21;
    public static final int STOP_HANDLER = 22;
    @ViewInject(R.id.iv_publish)
    private ImageView mImageViewPublish;
    @ViewInject(R.id.recv_business_circle)
    private SuperRecyclerView recyclerViewBusiness;
//    @ViewInject(R.id.ll_input)
//    private LinearLayout mLayoutInput;
    @ViewInject(R.id.root_view)
    private View parentView;
    @ViewInject(R.id.ll_empty_view)
    private LinearLayout mLayoutEmpty;
    @ViewInject(R.id.tv_publish)
    private TextView textViewPublish;
//    @ViewInject(R.id.edt_input)
//    private EditText editText;
//    @ViewInject(R.id.tv_send)
//    private TextView mTextViewSend;


    private YunShlPopupWinow popupWinow;
    private View view;
    private static final int REQUEST_SELECT_PHOTO = 0x11;  //图片
    private static final int  REQUEST_SELECT_VIDEO = 0x12; // 视频
    private static final int CLIP_PHOTO = 0x13;
    private CircleListAdapter mAdapter;
    private View commentView;
    private YunShlPopupWinow popupWindow;
    private Subscription subscription;
    private DynamicBean mCurrentDynamic;
    private long lastTime;
    private BusiHandler mHandler;
    private long newestTime;//最新一条动态的时间


    @Override
    public void init() {
        mAdapter = new CircleListAdapter(getActivity());
        mHandler = new BusiHandler(this);
        recyclerViewBusiness.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerViewBusiness.setAdapter(mAdapter);
        recyclerViewBusiness.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                lastTime = 0;
                getList(lastTime);
            }
        });
        initData();
        bindEvents();
    }

    private void bindEvents() {
        mImageViewPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getActivity(),ReleaseDynamicActivity.class), REQUEST_PUBLISH);
           //     showDialog();
            }
        });

        RxBus.getInstance().toObserverable(SubscriptionBean.RxBusSendBean.class).subscribe(new Action1<SubscriptionBean.RxBusSendBean>() {
            @Override
            public void call(SubscriptionBean.RxBusSendBean rxBusSendBean) {
                if (rxBusSendBean.type == RxEventType.UPDATE_DYNAMIC) {
                    DynamicBean dynamicBean = (DynamicBean) rxBusSendBean.content;
                    mAdapter.changeData(dynamicBean);
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {

            }
        });

        textViewPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getActivity(),ReleaseDynamicActivity.class), REQUEST_PUBLISH);
            }
        });
        NimManager.getInstance().addNotificationListener(this);

    }


    private void initData() {
        //mAdapter.setDatas(DynamicBean.createData());
        mAdapter.setOperationListener(this);
        lastTime = 0;
        getList(lastTime);
    }

    private void getList(long lastTime) {
        WPHSdk.getService(BusinessService.class)
                .getAllDynamic(lastTime, new YRequestCallback<DynamicPageData>() {
                    @Override
                    public void onSuccess(DynamicPageData var1) {
                        setPageData(var1);
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        recyclerViewBusiness.setRefreshing(false);
                    }

                    @Override
                    public void onException(Throwable var1) {
                        recyclerViewBusiness.setRefreshing(false);
                    }
                });
    }


    private void showCommentWindow(final DynamicBean dynamicBean, View view, int toUserId, String toUserName, final int position) {
        if (commentView == null) {
            commentView = LayoutInflater.from(getActivity()).inflate(R.layout.view_popupwindow_comment, null);
            popupWindow = new YunShlPopupWinow(commentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            popupWindow.setAnimation(getActivity(),false, R.style.dialog_right_left_scale_animation);
        }
        mCurrentDynamic = dynamicBean;
        LinearLayout linearLayoutComment = (LinearLayout) commentView.findViewById(R.id.ll_comment);
        LinearLayout linearLayoutUp = (LinearLayout) commentView.findViewById(R.id.ll_thumb_up);
        final TextView textView = (TextView) commentView.findViewById(R.id.tv_like_or_cancel);
        if (Build.VERSION.SDK_INT < 24) {
            popupWindow.showAsDropDown(view, -DensityUtil.dip2px(151), -DensityUtil.dip2px(32));
        }else {
            popupWindow.showAsDropDown(view, DensityUtil.dip2px(35), -DensityUtil.dip2px(4f),Gravity.RIGHT|Gravity.TOP);
        }
        if (dynamicBean.haveILike(WPHSdk.getService(OAuthService.class).getUserId())) {
            textView.setText("取消");
        }else {
            textView.setText("赞");
        }
        linearLayoutComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerViewBusiness.getRecyclerView().scrollToPosition(position);
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
                InputActivity.start(getActivity(), "评论", new InputActivity.InputActivityProxy() {
                    @Override
                    public void onSendMessage(String text) {
                        commentDynamic(dynamicBean.getId(),0,text);
                    }

                    @Override
                    public void onSofeInputSize(int currentSize) {

                    }
                });

            }
        });
        linearLayoutUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
                likeDynamic(dynamicBean.getId(),"赞".equals(textView.getText()));
            }
        });
    }

    private void likeDynamic(int dynamicId, boolean like) {
        WPHSdk.getService(BusinessService.class).addOrCancelLike(dynamicId, like, new YRequestCallback<List<ThumbUpBean>>() {
            @Override
            public void onSuccess(List<ThumbUpBean> var1) {
                mCurrentDynamic.setLikeList(var1);
                mAdapter.changeData(mCurrentDynamic);
            }

            @Override
            public void onFailed(int var1, String message) {

            }

            @Override
            public void onException(Throwable var1) {
                var1.printStackTrace();
            }
        });
    }


    public View getImageView(int index) {
        return mAdapter.getContentView(index);
    }

    private void commentDynamic(int dynamic,int userId, String content) {
        WPHSdk.getService(BusinessService.class).commentDynamic(dynamic, userId, content, new YRequestCallback<List<CommentBean>>() {
            @Override
            public void onSuccess(List<CommentBean> var1) {
                mCurrentDynamic.setReplyList(var1);
                mAdapter.changeData(mCurrentDynamic);
            }

            @Override
            public void onFailed(int var1, String message) {
                ToastManager.getInstance().showToast(message);
            }

            @Override
            public void onException(Throwable var1) {
                var1.printStackTrace();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
        NimManager.getInstance().removeNotificationListener(this);
    }

    @Override
    public void onCommentClick(DynamicBean dynamicBean, View parentView, int toUserId, String toUserName, int position) {
        showCommentWindow(dynamicBean, parentView,toUserId,toUserName,position);
    }

    @Override
    public void onCommentPerson(final DynamicBean dynamicBean, CommentBean bean, final int toUserId, String toUserName, int position) {
        mCurrentDynamic = dynamicBean;
        int myId = WPHSdk.getService(OAuthService.class).getUserId();
        if (toUserId == myId) {
            showDeleteDialog(bean.getId());
        }else {
            InputActivity.start(getActivity(), dynamicBean.getUser_id() == toUserId ? "评论" : "回复" + toUserName + ":", new InputActivity.InputActivityProxy() {
                @Override
                public void onSendMessage(String text) {
                    commentDynamic(dynamicBean.getId(), toUserId, text);
                }

                @Override
                public void onSofeInputSize(int currentSize) {

                }
            });
        }
    }


    @Override
    public void onUsreDynamic(int userId, String name) {
        Intent intent = new Intent(getActivity(), CustomerInfoActivity.class);
        intent.putExtra("user_id", userId);
        startActivity(intent);
    }

    @Override
    public void onDeleteDynamic(final DynamicBean dynamicBean) {
        if (dynamicBean == null)return;
        BaseDialogManager.getInstance().getBuilder(getActivity())
                .setIcon(ContextCompat.getDrawable(getActivity(), R.mipmap.dialog_box_icon_business))
                .setTitle("是否删除该生意圈")
                .setLeftButtonText("是")
                .setRightButtonText("否")
                .setOnClickListener(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (which == BaseDialogManager.LEFT_BUTTON) {
                            WPHSdk.getService(BusinessService.class)
                                    .deleteDynamic(dynamicBean.getId(), new YRequestCallback<Object>() {
                                        @Override
                                        public void onSuccess(Object var1) {
                                            mAdapter.deleteDynamic(dynamicBean);
                                            if (mAdapter.getItemCount() > 0) {
                                                mLayoutEmpty.setVisibility(View.GONE);
                                            }else {
                                                mLayoutEmpty.setVisibility(View.VISIBLE);
                                            }
                                        }

                                        @Override
                                        public void onFailed(int var1, String message) {

                                        }

                                        @Override
                                        public void onException(Throwable var1) {

                                        }
                                    });
                        }
                    }
                }).create().show();
    }


    private void setPageData(DynamicPageData var1) {
        recyclerViewBusiness.setRefreshing(false);
        if (lastTime == 0) {
            mAdapter.setDatas(var1.getPdList());
            if (var1.getPdList() != null && var1.getPdList().size() > 0) {
                newestTime = var1.getPdList().get(0).getCreated_at();
            }
            if (getActivity() != null) {
                ((HomePageActivity)getActivity()).hideDynamicNewPoint();
            }
        }else {
            mAdapter.addDatas(var1.getPdList());
        }
        if (mAdapter.getItemCount() > 0) {
            mLayoutEmpty.setVisibility(View.GONE);
        }else {
            mLayoutEmpty.setVisibility(View.VISIBLE);
        }
        if (var1.getPdList() != null && var1.getPdList().size() > 0) {
            lastTime = var1.getPdList().get(var1.getPdList().size()-1).getCreated_at();
        }
        if (var1.getPdList() != null && var1.getPdList().size() < 20) {
            recyclerViewBusiness.removeMoreListener();
            recyclerViewBusiness.hideMoreProgress();
        }else {
            recyclerViewBusiness.setupMoreListener(new OnMoreListener() {
                @Override
                public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
                    getList(lastTime);
                }
            },1);
        }
    }

    private void deleteComment(int commentId) {
        WPHSdk.getService(BusinessService.class)
                .deleteComment(commentId, new YRequestCallback<List<CommentBean>>() {
                    @Override
                    public void onSuccess(List<CommentBean> var1) {
                        mCurrentDynamic.setReplyList(var1);
                        mAdapter.changeData(mCurrentDynamic);
                    }

                    @Override
                    public void onFailed(int var1, String message) {

                    }

                    @Override
                    public void onException(Throwable var1) {

                    }
                });
    }

    private void showDeleteDialog(final int commentId) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_pwin_delete_comment, null);
        final YunShlPopupWinow winow = new YunShlPopupWinow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        winow.setCommonConfig(getActivity(), YunShlPopupWinow.AnimaDirect.DIRECT_BOTTOM_TOP);
        TextView textViewDelete = (TextView) view.findViewById(R.id.tv_delete);
        TextView textViewCancel = (TextView) view.findViewById(R.id.tv_cancel);
        textViewCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (winow != null) {
                    winow.dismiss();
                }
            }
        });
        textViewDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (winow != null) {
                    winow.dismiss();
                }
                deleteComment(commentId);
            }
        });
        winow.showAtLocation(getActivity().findViewById(R.id.root_view),Gravity.BOTTOM,0,0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PUBLISH && resultCode == Activity.RESULT_OK) {
            lastTime = 0;
            getList(lastTime);
        }
    }

    @Override
    public void onReceiveNotification(long messageTime, CustomerNotificationContent content) {
        if (content != null && content.getType() == 0) {
            if (newestTime*1000 < messageTime) {
                //最新一条的时间比通知时间早，显示有更新
                try {
                    ((HomePageActivity)getActivity()).showDynamicNewPoint();
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static class BusiHandler extends Handler {
        private WeakReference<BusinessCircleFragment> reference;
        public BusiHandler(BusinessCircleFragment fragment) {
            reference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_HAVE_NEW:
                    break;

                case STOP_HANDLER:
                    break;
            }
        }
    }
}
